﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Zatify.Domain.Abstract;
using Zatify.WebUI.Infrastructure;
using Zatify.WebUI.Models;
using Zatify.Domain.Data;
using Zatify.Domain.Helpers;

namespace Zatify.WebUI.Controllers
{
    public enum BlockType
    {
        Promotion = 1,
        Business = 2,
        Category = 3
    }

    [Authorize]
    public class UserProfileController : BaseController
    {
        private IZatifyRepository repository;
        private IDistanceCalculator distanceCalculator;

        public UserProfileController(IZatifyRepository repository, IDistanceCalculator distanceCalculator)
        {
            this.repository = repository;
            this.distanceCalculator = distanceCalculator;
        }

        #region GeneralInfo

        [HttpGet]
        public ActionResult GeneralInfo()
        {
            var user = this.repository.UserGetByToken(User.SecurityToken.Value);

            return View(new UserProfileGeneralInfoViewModel()
            {
                UserId = user.Login,
                Password = user.Password,
                ConfirmPassword = user.Password,
                Email = user.Email,
                Phone = user.Phone,
                PictureContentType = user.PhotoContentType,
                Picture = user.Photo,
                ZipCode = user.ZipCode
            });
        }

        [HttpPost]
        public ActionResult GeneralInfo(UserProfileGeneralInfoViewModel model, string imagePath)
        {
            if (this.ModelState.IsValid)
            {
                if (!String.IsNullOrWhiteSpace(imagePath))
                {
                    var filePath = Server.MapPath(imagePath);
                    var fileInfo = new System.IO.FileInfo(filePath);

                    using (var fsStream = System.IO.File.OpenRead(filePath))
                    {
                        model.Picture = new byte[fsStream.Length];
                        model.PictureContentType = "image/" + fileInfo.Extension.Replace(".", String.Empty);
                        fsStream.Read(model.Picture, 0, (int)fsStream.Length);
                    }
                }
                //else
                //{
                //    this.ModelState.AddModelError("ProfileImage", "Select Profile Image");
                //    return View(model);
                //}

                var result = this.repository.UserUpdateByToken(User.SecurityToken.Value,
                    new User()
                    {
                        Password = model.Password,
                        Email = model.Email,
                        Phone = model.Phone,
                        PhotoContentType = model.PictureContentType,
                        Photo = model.Picture,
                        ZipCode = model.ZipCode
                    });

                if (result == 0)
                {
                    this.ModelState.AddModelError("UserUpdate", "Error while updating profile");
                    return View(model);
                }
            }

            System.IO.File.Delete(Server.MapPath(imagePath));
            return RedirectToAction("GeneralInfo", "UserProfile");
        }

        #endregion

        #region Settings

        [HttpGet]
        public ActionResult Settings()
        {
            return View(new UserProfileSettingsViewModel()
            {
                AlertMode = this.repository.UserSettingsGetByToken(User.SecurityToken.Value).AlertMode
            });
        }

        [HttpPost]
        public ActionResult Settings(UserProfileSettingsViewModel model)
        {
            if (ModelState.IsValid)
            {
                this.repository.UserSettingsUpdateByToken(User.SecurityToken.Value, "AlertMode", model.AlertMode.ToString());
            }

            return View(model);
        }

        #endregion

        #region Categories

        [HttpGet]
        public ActionResult Categories(int? categoryId)
        {
            var selectedCategories = this.repository.UserGetCategories(User.SecurityToken.Value);

            return View(new UserProfileCategoriesViewModel()
            {
                SelectegCategoriesIds = String.Join(",", (from cat in selectedCategories select cat.CategoryId)),
                SelectedCategories = selectedCategories,
                CurrentCategory = repository.Categories.FirstOrDefault(c => c.CategoryId == categoryId),
                Categories = repository.CategoriesGetAll().Where(c => c.ParentId == categoryId).ToList()
            });
        }

        [HttpPost]
        public ActionResult Categories(string categoriesIds)
        {
            if (!String.IsNullOrWhiteSpace(categoriesIds))
            {
                repository.UserAddCategories(User.SecurityToken.Value, categoriesIds);
            }

            return RedirectToAction("Deals");
        }

        [HttpGet]
        public ActionResult CategoriesEdit()
        {
            var selectedCategories = this.repository.UserGetCategories(User.SecurityToken.Value);

            return View(new UserProfileCategoriesEditViewModel()
            {
                SelectegCategoriesIds = String.Join(",", (from cat in selectedCategories select cat.CategoryId)),
                SelectedCategories = selectedCategories,
                AllCategories = repository.CategoriesGetAll().ToList()
            });
        }

        [HttpPost]
        public ActionResult CategoriesRemove(string categoriesIds)
        {
            //if (!String.IsNullOrEmpty(categoriesIds))
            //{
            this.repository.UserUpdateCategories(User.SecurityToken.Value, categoriesIds);
            //}

            return RedirectToAction("CategoriesEdit");
        }

        #endregion

        #region Search

        private readonly int pageSearchSize = 6;

        public ActionResult Search(string search, int page = 1)
        {
            var businesses = this.repository.BusinessesSearch(User.SecurityToken.Value, search ?? String.Empty, null, null).ToList();
            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            //businesses.Skip((page - 1) * pageSearchSize).Take(pageSearchSize).ToList().ForEach(b =>
            businesses.ToList().ForEach(b =>
            {
                if (b.Latitude.HasValue && b.Longitude.HasValue)
                {
                    b.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = b.Latitude.Value,
                         Longitude = b.Longitude.Value
                     });
                }
            });

            return View(new UserProfileBusinessesSearchViewModel()
            {
                Search = search ?? String.Empty,
                //Businesses = businesses.Skip((page - 1) * pageSearchSize).Take(pageSearchSize).ToList(),
                Businesses = businesses.OrderBy(b => b.Distance).Skip((page - 1) * pageNearbySize).Take(pageNearbySize).ToList(),
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageSearchSize,
                    TotalItems = businesses.Count
                }
            });
        }

        #endregion

        #region Nearby

        private readonly int pageNearbySize = 6;

        //[HttpGet]
        public ActionResult Nearby(int page = 1)
        {
            var businesses = this.repository.BusinessesGetUserNearby(User.SecurityToken.Value, User.ZipCode).ToList();
            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            //businesses.Skip((page - 1) * pageSearchSize).Take(pageSearchSize).ToList().ForEach(b =>
            businesses.ToList().ForEach(b =>
            {
                if (b.Latitude.HasValue && b.Longitude.HasValue)
                {
                    b.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = b.Latitude.Value,
                         Longitude = b.Longitude.Value
                     });
                }
            });

            return View(new UserProfileBusinessesNearbyViewModel()
            {
                //Businesses = businesses.Skip((page - 1) * pageNearbySize).Take(pageNearbySize).OrderBy(b => b.Distance).ToList(),
                Businesses = businesses.OrderBy(b => b.Distance).Skip((page - 1) * pageNearbySize).Take(pageNearbySize).ToList(),
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageNearbySize,
                    TotalItems = businesses.Count
                }
            });
        }

        //[HttpPost]
        //public ActionResult Nearby(int page = 1)
        //{
        //    var businesses = this.repository.BusinessesGetUserNearby(User.SecurityToken.Value, null, null).ToList();

        //    return View(new UserProfileBusinessesNearbyViewModel()
        //    {
        //        Businesses = businesses.Skip((page - 1) * pageNearbySize).Take(pageNearbySize).ToList(),
        //        PagingInfo = new PagingInfo()
        //        {
        //            CurrentPage = page,
        //            ItemsPerPage = pageNearbySize,
        //            TotalItems = businesses.Count
        //        }
        //    });
        //}

        #endregion

        #region Favorites

        private readonly int pageFavoritesSize = 6;

        [HttpGet]
        public ActionResult Favorites(int page = 1)
        {
            var favorites = this.repository.BusinessesGetUserFavorites(User.SecurityToken.Value, null, null).ToList();
            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            favorites.Skip((page - 1) * pageSearchSize).Take(pageSearchSize).ToList().ForEach(b =>
            {
                if (b.Latitude.HasValue && b.Longitude.HasValue)
                {
                    b.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = b.Latitude.Value,
                         Longitude = b.Longitude.Value
                     });
                }
            });

            return View(new UserProfileBusinessesFavoritesViewModel()
            {
                FavoriteBusinesses = favorites.Skip((page - 1) * pageFavoritesSize).Take(pageFavoritesSize).ToList(),
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageFavoritesSize,
                    TotalItems = favorites.Count
                }
            });
        }

        [HttpGet]
        public ActionResult FavoritesEdit(int page = 1)
        {
            var favorites = this.repository.BusinessesGetUserFavorites(User.SecurityToken.Value, null, null).ToList();
            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            favorites.Skip((page - 1) * pageSearchSize).Take(pageSearchSize).ToList().ForEach(b =>
            {
                if (b.Latitude.HasValue && b.Longitude.HasValue)
                {
                    b.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = b.Latitude.Value,
                         Longitude = b.Longitude.Value
                     });
                }
            });

            return View(new UserProfileBusinessesFavoritesViewModel()
            {
                FavoriteBusinesses = favorites.Skip((page - 1) * pageFavoritesSize).Take(pageFavoritesSize).ToList(),
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageFavoritesSize,
                    TotalItems = favorites.Count
                }
            });
        }

        [HttpPost]
        public ActionResult FavoritesDelete(string businessesIds)
        {
            if (!String.IsNullOrEmpty(businessesIds))
            {
                this.repository.UserFavoriteBusinessesDelete(User.SecurityToken.Value, businessesIds.ToString());
                return RedirectToAction("Favorites");
            }
            else
            {
                return RedirectToAction("FavoritesEdit");
            }
        }

        public ActionResult FavoritesAdd(int businessId)
        {
            this.repository.UserFavoriteBusinessesAdd(User.SecurityToken.Value, businessId.ToString());

            return RedirectToAction("BusinessDetails", new { id = businessId });
        }

        public ActionResult FavoritesDelete(int businessId)
        {
            this.repository.UserFavoriteBusinessesDelete(User.SecurityToken.Value, businessId.ToString());

            return RedirectToAction("BusinessDetails", new { id = businessId });
        }

        #endregion

        #region Deals/Promotions

        private readonly int pageDealsSize = 6;

        [HttpGet]
        public ActionResult Deals(int page = 1)
        {
            var geoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);
            var promotions = this.repository.Deals(User.SecurityToken.Value, geoLocation.Lat, geoLocation.Long).ToList();

            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            promotions.Skip((page - 1) * pageSearchSize).Take(pageSearchSize).ToList().ForEach(p =>
            {
                if (p.Business.Latitude.HasValue && p.Business.Longitude.HasValue)
                {
                    p.Business.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = p.Business.Latitude.Value,
                         Longitude = p.Business.Longitude.Value
                     });
                }
            });

            return View(new UserProfileBusinessesDealsViewModel()
            {

                Promotions = promotions.Skip((page - 1) * pageDealsSize).Take(pageDealsSize).ToList(),
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageDealsSize,
                    TotalItems = promotions.Count
                }
            });
        }

        [HttpGet]
        public ActionResult PromotionDetails(int id)
        {
            var promotion = this.repository.PromotionGetById(id);

            var hoursToday = this.repository.BusinessGetBusinessHoursToday(promotion.Business.BusinessId);
            promotion.Business.FromToday = hoursToday.FromTime.Value.TimeOfDay;
            promotion.Business.ToToday = hoursToday.ToTime.Value.TimeOfDay;
            promotion.Business.StatusToday = hoursToday.Status;
            promotion.Business.ClosedToday = hoursToday.Closed.Value;

            return View(new UserProfilePromotionDetailsViewModel()
            {
                Promotion = promotion,
                IsUserFavorite = this.repository.BusinessesGetUserFavorites(User.SecurityToken.Value, null, null).Select(f => f.BusinessId).ToList().Contains(promotion.BusinessId),
            });
        }

        public ActionResult PromotionFavoritesAdd(int businessId, int promotionId)
        {
            this.repository.UserFavoriteBusinessesAdd(User.SecurityToken.Value, businessId.ToString());

            return RedirectToAction("PromotionDetails", new { id = promotionId });
        }

        public ActionResult PromotionFavoritesDelete(int businessId, int promotionId)
        {
            this.repository.UserFavoriteBusinessesDelete(User.SecurityToken.Value, businessId.ToString());

            return RedirectToAction("PromotionDetails", new { id = promotionId });
        }

        [HttpPost]
        public ActionResult Block(int promotionId, BlockType blockType)
        {
            var promotion = this.repository.PromotionGetById(promotionId);

            switch (blockType)
            {
                case BlockType.Business:
                    this.repository.UserBlockBusinesses(User.SecurityToken.Value, promotion.BusinessId.ToString());
                    break;
                case BlockType.Category:
                    string categoryIds = "";
                    if (promotion.Categories != null)
                        if (promotion.Categories.Count() > 0)
                        {
                            foreach(Category c in promotion.Categories)
                            {
                                if (!string.IsNullOrEmpty(categoryIds))
                                    categoryIds += ",";
                                categoryIds += c.CategoryId.ToString();
                            }
                            this.repository.UserBlockCategories(User.SecurityToken.Value, categoryIds);
                        }
                    break;
                case BlockType.Promotion:
                    this.repository.UserBlockPromotions(User.SecurityToken.Value, promotionId.ToString());
                    break;
            }
            
            //return RedirectToAction("PromotionDetails", new { id = promotionId });
            return RedirectToAction("Deals");
        }


        public ActionResult ActivePromotions(int id, int page = 1)
        {
            var promotions = this.repository.BusinessGetAllActivePromotions(User.SecurityToken.Value, id, null, null).ToList();

            return View(new UserProfileBusinessActivePromotionsViewModel()
            {
                Promotions = promotions.Skip((page - 1) * pageDealsSize).Take(pageDealsSize).ToList(),
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageDealsSize,
                    TotalItems = promotions.Count
                }
            });
        }

        #endregion

        #region CheckIn

        [HttpGet]
        public ActionResult CheckIn()
        {
            return View(new CheckInViewModel());
        }

        [HttpPost]
        public ActionResult CheckIn(CheckInViewModel model)
        {
            if (ModelState.IsValid)
                return View(new CheckInViewModel());

            return View(new CheckInViewModel());
        }

        #endregion

        public ActionResult SearchMap(string search)
        {
            var model = new MapViewModel()
            {
                PageTitle = "Search",
                ReturnUrl = Url.Action("Search", new { search = search }),
                GeoLocations = this.repository.GeoLocation_GetList(),
                Businesses = this.repository.BusinessesSearch(User.SecurityToken.Value, search ?? String.Empty, null, null).ToList(),
                CenterCoordinates = new GeoLocationCoordinates()
                {
                    Latitude = 36.1661339,
                    Longitude = -115.2458037
                },
                ShowCityStateSelector = true
            };

            return View("Map", model);
        }

        public ActionResult NearbyMap()
        {
            var geoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            var model = new MapViewModel()
            {
                PageTitle = "Nearby",
                ReturnUrl = "Nearby",
                GeoLocations = this.repository.GeoLocation_GetList(),
                Businesses = this.repository.BusinessesGetUserNearby(User.SecurityToken.Value, User.ZipCode).ToList(),
                //this.repository.BusinessesSearch(User.SecurityToken.Value, String.Empty, geoLocation.Lat, geoLocation.Long).ToList(),
                CenterCoordinates = new GeoLocationCoordinates()
                {
                    Latitude = geoLocation.Lat.Value,
                    Longitude = geoLocation.Long.Value
                },
                ShowCityStateSelector = true
            };

            return View("Map", model);
        }

        public ActionResult DealsMap()
        {
            var model = new DealsMapViewModel()
            {
                PageTitle = "Deals",
                ReturnUrl = "Deals",
                GeoLocations = this.repository.GeoLocation_GetList(),
                Promotions = this.repository.Deals(User.SecurityToken.Value, null, null).ToList(),
                CenterCoordinates = new GeoLocationCoordinates()
                {
                    Latitude = 36.1661339,
                    Longitude = -115.2458037
                },
                ShowCityStateSelector = true
            };

            return View("DealsMap", model);
        }

        public JsonResult GetLocations(string city)
        {
            return Json(new { locations = this.repository.GeoLocation_GetList().Where(x => x.City.ToLower().StartsWith(city.ToLower())) }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult BusinessDetails(int id)
        {
            if (id > 0)
            {
                var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);
                var business = this.repository.BusinessGetById(id);
                business.BusinessHours = this.repository.BusinessGetBusinessHours(business.BusinessId);

                var hoursToday = this.repository.BusinessGetBusinessHoursToday(business.BusinessId);
                business.FromToday = hoursToday.FromTime.Value.TimeOfDay;
                business.ToToday = hoursToday.ToTime.Value.TimeOfDay;
                business.StatusToday = hoursToday.Status;
                business.ClosedToday = hoursToday.Closed.Value;

                if (business.Latitude.HasValue && business.Longitude.HasValue)
                {
                    business.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = business.Latitude.Value,
                         Longitude = business.Longitude.Value
                     });
                }

                var isUserFavorite = this.repository.BusinessesGetUserFavorites(User.SecurityToken.Value, null, null).Select(f => f.BusinessId).ToList().Contains(id);

                var model = new UserProfileBusinessesDetailsViewModel()
                {
                    Business = business,
                    IsUserFavorite = isUserFavorite
                };

                return View(model);
            }
            else
            {
                return RedirectToAction("Favorites");
            }
        }

        public ActionResult BusinessMoreInfo(int id)
        {
            if (id > 0)
            {
                var business = this.repository.BusinessGetById(id);
                var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

                business.BusinessHours = this.repository.BusinessGetBusinessHours(business.BusinessId);

                business.Distance = distanceCalculator.Calculate(

                         new Zatify.Domain.Concrete.ZipCode()
                         {
                             Latitude = usersGeoLocation.Lat.Value,
                             Longitude = usersGeoLocation.Long.Value
                         },
                         new Zatify.Domain.Concrete.ZipCode()
                         {
                             Latitude = business.Latitude.Value,
                             Longitude = business.Longitude.Value
                         });


                return View(business);
            }
            else
            {
                return RedirectToAction("Favorites");
            }
        }

        public ActionResult BusinessDirection(int id)
        {
            var business = this.repository.BusinessGetById(id);

            if (business != null)
            {
                var geoLocation = this.repository.GeoLocation_GetByZipCode(business.ZipCode);

                var model = new MapViewModel()
                {
                    PageTitle = "Direction",
                    ReturnUrl = Url.Action("BusinessDetails", new { id = id }),
                    //GeoLocations = this.repository.GeoLocation_GetList(),
                    Businesses = new List<Business>(new Business[] { business }),
                    CenterCoordinates = new GeoLocationCoordinates()
                    {
                        Latitude = geoLocation.Lat.Value,
                        Longitude = geoLocation.Long.Value
                    },
                    ShowCityStateSelector = false
                };

                return View("Map", model);
            }

            return RedirectToAction("Search");
        }

        #region Reviews

        public ActionResult BusinessReviews(int businessId)
        {
            var business = this.repository.BusinessGetById(businessId);
            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            business.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = business.Latitude.Value,
                         Longitude = business.Longitude.Value
                     });

            return View(new UserProfileBusinessReviewsViewModel()
            {
                Business = business,
                Reviews = this.repository.BusinessGetReviews(User.SecurityToken.Value, businessId).ToList()
            });
        }

        [HttpGet]
        public ActionResult ReviewAdd(int businessId)
        {
            var business = this.repository.BusinessGetById(businessId);
            var usersGeoLocation = this.repository.GeoLocation_GetByZipCode(User.ZipCode);

            business.Distance = distanceCalculator.Calculate(

                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = usersGeoLocation.Lat.Value,
                         Longitude = usersGeoLocation.Long.Value
                     },
                     new Zatify.Domain.Concrete.ZipCode()
                     {
                         Latitude = business.Latitude.Value,
                         Longitude = business.Longitude.Value
                     });

            return View(new UserProfileBusinessReviewViewModel()
            {
                BusinessId = business.BusinessId,
                BusinessDistance = business.Distance,
                BusinessName = business.BusinessName,
                BusinessAddress = business.StreetAddress1,
                ReviewText = String.Empty,
                Rating = 0
            });
        }

        [HttpPost]
        public ActionResult ReviewAdd(UserProfileBusinessReviewViewModel model)
        {
            if (ModelState.IsValid)
            {
                this.repository.BusinessReviewAdd(User.SecurityToken.Value, model.BusinessId, model.ReviewText, model.Rating);
            }
            else
            {
                return View(model);
            }

            return RedirectToAction("BusinessReviews", new { businessId = model.BusinessId });
        }

        #endregion

        #region Helper Methods

        public FileContentResult GetUserPhoto()
        {
            var user = this.repository.UserGetByToken(User.SecurityToken.Value);

            if (user != null && user.Photo != null)
                return File(user.Photo, user.PhotoContentType);
            else
                return null;
        }

        public FileContentResult GetUserPhotoById(int id, int w, int h)
        {
            var user = this.repository.GetUserById(id);

            if (user != null && user.Photo != null)
            {
                var newSizedImg = Helper.ScaleImage(user.Photo, w, h);
                byte[] newSizedImgBytes = Helper.ImageToByteArray(newSizedImg);

                return File(newSizedImgBytes, user.PhotoContentType);
            }
            else
            {
                var newSizedImg = Helper.ScaleImage(System.IO.File.ReadAllBytes(Server.MapPath("~/Content/zatify/images/no_image.jpg")), w, h);
                byte[] newSizedImgBytes = Helper.ImageToByteArray(newSizedImg);

                return File(newSizedImgBytes, "image/jpeg");
            }
        }

        public FileContentResult GetBusinessPhoto(int businessId, int w, int h)
        {
            var business = this.repository.BusinessGetById(businessId);

            if (business != null && business.Picture != null)
            {
                var newSizedImg = Helper.ScaleImage(business.Picture, w, h);
                byte[] newSizedImgBytes = Helper.ImageToByteArray(newSizedImg);

                return File(/*business.Picture*/ newSizedImgBytes, business.PictureContentType);
            }
            else
            {
                var newSizedImg = Helper.ScaleImage(System.IO.File.ReadAllBytes(Server.MapPath("~/Content/zatify/images/no_image.jpg")), w, h);
                byte[] newSizedImgBytes = Helper.ImageToByteArray(newSizedImg);

                return File(newSizedImgBytes, "image/jpeg");
            }
        }

        public FileContentResult GetPromotionPhoto(int promotionId, int w, int h)
        {
            var promotion = this.repository.PromotionGetById(promotionId);

            if (promotion != null && promotion.Picture != null)
            {
                var newSizedImg = Helper.ScaleImage(promotion.Picture, w, h);
                byte[] newSizedImgBytes = Helper.ImageToByteArray(newSizedImg);

                return File(newSizedImgBytes, promotion.PictureContentType);
            }
            else
            {
                var newSizedImg = Helper.ScaleImage(System.IO.File.ReadAllBytes(Server.MapPath("~/Content/zatify/images/no_image.jpg")), w, h);
                byte[] newSizedImgBytes = Helper.ImageToByteArray(newSizedImg);

                return File(newSizedImgBytes, "image/jpeg");
            }
        }

        #endregion
    }
}
